import { defineStore } from 'pinia'
import { register, login, TABLE_INDEX } from '@/api/user'
import type { User } from '@/models/user.model'

export const useUserStore = defineStore('user', {
  state: () => ({
    user: null as User | null,
    token: localStorage.getItem('token') || null,
    isLoggedIn: !!localStorage.getItem('token')
  }),
  actions: {
    // 用户注册
    async register(userData: User) {
      try {
        const response = await register(userData)
        ElMessage.success('注册成功')
        return response
      } catch (error) {
        throw error
      }
    },
    
    // 用户登录
    async login(username: string, password: string) {
      try {
        const response = await login(username, password)
        this.token = response.token
        this.user = response.user
        this.isLoggedIn = true
        localStorage.setItem('token', response.token)
        ElMessage.success('登录成功')
        return response
      } catch (error) {
        throw error
      }
    },
    
    // 退出登录
    logout() {
      this.user = null
      this.token = null
      this.isLoggedIn = false
      localStorage.removeItem('token')
    }
  },
  persist: true // 启用数据持久化
})